package web

import (
	"commerce/common"
	"commerce/data"
	"commerce/model"
	"commerce/req"
	"commerce/utils"
	"commerce/vo"
	"encoding/json"
	"net/http"
)

/* 此文件是 app 意见反馈 请求 */

func SaveFeedbackHandler(w http.ResponseWriter, r *http.Request) {

	member := extractUserFromContext(r)
	if member == nil || member.Mid <= 0 {
		common.DisplayTokenErr(w, http.StatusUnauthorized)
		return
	}
	var feedbackReq req.AddFeedbackReq
	err := json.NewDecoder(r.Body).Decode(&feedbackReq)
	if err != nil {
		common.Error.Printf("SaveFeedbackHandler err:%v", err)
		j, _ := json.Marshal(vo.Err(err.Error()))
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write(j)
		return
	}
	_, err = data.AddFeedback(model.Feedback{MemberId: member.Mid, MemberName: member.Mnickname,
		MemberIp: utils.ClientPublicIP(r), Phone: feedbackReq.Mobile, Type: feedbackReq.Index, Content: feedbackReq.Content})
	if err != nil {
		common.Error.Printf("SaveFeedbackHandler err:%v", err)
		j, _ := json.Marshal(vo.Err(err.Error()))
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write(j)
		return
	}
	j, _ := json.Marshal(vo.Ok("反馈成功！"))
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	w.Write(j)
}
